﻿using RAP.Framework.Libary.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;

namespace RAP.Framework.Libary.SqlTaskParser.Parsers
{
  public abstract class TokenParserBase : ISqlTokenParser
  {
    /// <summary>
    /// 自定义Token的正则表达式匹配规则
    /// </summary>
    public virtual string CustomerRegex { get; set; }

    public virtual void ParseToken(SqlParseContext context)
    {
      this.ReplaceToken(context);
    }

    /// <summary>
    /// 获取当前Token的SqlGrammar
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public string GetSqlGrammarOption(SqlParseContext context)
    {
      var task = context.CurrentTask;
      if (task == null)
      {
        return string.Empty;
      }
      var dataSourceOptions = context.DataSourceConfig.DataSources[task.DataSourceId];
      var sqlGrammar = dataSourceOptions.FirstItem().SqlGrammar; // 只按照第一个数据源的参数处理
      return sqlGrammar;
    }

    /// <summary>
    /// 替换token为其它字符串，默认删除
    /// </summary>
    /// <param name="context"></param>
    /// <param name="replace"></param>
    protected virtual void ReplaceToken(SqlParseContext context, string replace = "")
    {
      var currentTask = context.CurrentTask;
      var currentToken = context.CurrentToken;
      if (currentTask == null || currentToken == null)
      {
        return;
      }
      var tag = currentToken.PlaceholderTag;
      if (tag.IsNotNullOrEmpty())
      {
        currentTask.Sql = currentTask.Sql.Replace(tag, replace);
      }
    }
  }
}
